package kr.co.dayve.site.management.service;

import kr.co.dayve.site.domain.*;
import kr.co.dayve.site.management.dao.*;
import kr.co.dayve.site.management.util.DayveCommon;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.multipart.MultipartFile;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;


public class DayveServiceImpl implements DayveService {

    public List getMemberListBySearchword(Member member){
        return memberDao.getMemberListBySearchword(member);
    }

    public String getTotalMemberCountBySearchword(Member member){
        return memberDao.getTotalMemberCountBySearchword(member);
    }

    public String getName(String name) {
        String rtnName = "";
        return (new StringBuilder()).append(name).append(rtnName).toString();
    }

    public Member getMemberById(String id) {
        return memberDao.getMemberById(id);
    }

    public Member getMemberByEmail(String id){
        return memberDao.getMemberByEmail(id);
    }

    public Member getMemberByIdEmail(Member member){
        return memberDao.getMemberByIdEmail(member);
    }

    public String getMemberExistById(String id) {
        return memberDao.getMemberExistById(id);
    }

    public String getMemberExistByEmail(String email){
        return memberDao.getMemberExistByEmail(email);
    }

    public String getMemberExistByIdEmail(Member member){
        return memberDao.getMemberExistByIdEmail(member);
    }

    public String insertMember(Member member){
        return memberDao.insertMember(member);
    }

    public String updateMemberById(Member member){
        return memberDao.updateMemberById(member);
    }

    public String adminUpdateMemberById(Member member){
        return memberDao.adminUpdateMemberById(member);
    }


    public String updateMemberPasswordById(Member member){
        return memberDao.updateMemberPasswordById(member);
    }

    public String deleteMemberById(String id){
        return memberDao.deleteMemberById(id);
    }

    public String logIn(String id, String password) {



        String result = "";

        memberDao.getMemberExistById(id);

        if(("0").equals(memberDao.getMemberExistById(id))) {
            result = "NON_EXIST";
        } else {
            result = "EXIST";
        }
        if(("EXIST").equals(result)) {
            Member member = new Member();
            member.setId(id);

            DayveCommon common = new DayveCommon();
            member.setPassword(common.getEncodedPassword(password));
            if(Integer.parseInt((String)memberDao.logIn(member)) > 0) {
                return "SUCCESS";
            } else {
                return "FALSE";
            }
        }

        return result;
    }

    /**
     * MimeMessage 를 이용하는 MimeMessageHelper 를 이용해 메일 보내기
     * 미완성
     * @param subject
     * @param content
     * @param fromUser
     * @param toUser
     * @param userId
     */
    public String sendMail(String subject, String content, String fromUser, String toUser, String userId){

        MimeMessage message = mailSender.createMimeMessage();

        try{
            // messageHelper 에 들어갈 MimeMessage message, 첨부파일여부, 인코딩
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, false, "UTF-8");

            messageHelper.setSubject(subject); // 제목 셋팅
            messageHelper.setText(content, true); // 내용 셋팅
            messageHelper.setFrom(new InternetAddress(fromUser, "Dayve")); // 보낸사람 셋팅
            messageHelper.setTo(new InternetAddress(toUser, userId, "UTF-8")); // 받는 사람

            //DataSource dataSource = new FileDataSource()

            //messageHelper.addAttachment();

        }catch (Throwable e){

            return "메일 전송에 실패했습니다.";

        }
        try{
            mailSender.send(message);
            return "메일이 성공적으로 전송되었습니다.";

        }catch (MailException e){

            return "메일 전송에 실패했습니다.";

        }
    }

    public String sendImageMail(String subject, String content, String fromUser, String toUser, String userId, File file){

        MimeMessage message = mailSender.createMimeMessage();

        try{
            // messageHelper 에 들어갈 MimeMessage message, 첨부파일여부, 인코딩
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "UTF-8");

            messageHelper.setSubject(subject); // 제목 셋팅
            messageHelper.setText(content, true); // 내용 셋팅
            messageHelper.setFrom(new InternetAddress(fromUser, "Dayve")); // 보낸사람 셋팅
            messageHelper.setTo(new InternetAddress(toUser, userId, "UTF-8")); // 받는 사람

            FileSystemResource res = new FileSystemResource(file);
            messageHelper.addInline("pImage", res);


            //DataSource dataSource = new FileDataSource()

            //messageHelper.addAttachment();

        }catch (Throwable e){

            return "2";

        }
        try{
            mailSender.send(message);
            return "1";

        }catch (MailException e){

            return "2";

        }
    }

    public List getCategoryMemberListByCategoryName(Category category){
        return memberDao.getCategoryMemberListByCategoryName(category);
    }

    public List getItemMemberListByItemName(Item item){
        return memberDao.getItemMemberListByItemName(item);
    }



    public String writeContact(Contact contact){
        return contactDao.writeContact(contact);
    }

    public List getContactList(Contact contact){
        return contactDao.getContactList(contact);
    }

    public String getTotalContact(Contact contact){
        return contactDao.getTotalContact(contact);
    }

    public Contact getContactByNo(String contact_no){
        return contactDao.getContactByNo(contact_no);
    }

    public String updateContact(Contact contact){
        return contactDao.updateContact(contact);

    }



    public List getBoardListBySearchword(Board board) {
        return boardDao.getBoardListBySearchword(board);
    }

    public String getTotalCountBySearchword(Board board) {
        return boardDao.getTotalCountBySearchword(board);
    }

    public List getCountryList(){
        return countryDao.getCountryList();
    }

    public String getTotalCountCountry(){
        return countryDao.getTotalCountCountry();
    }

    public Country getCountryByCode(String country_code){
        return countryDao.getCountryByCode(country_code);
    }



    ///////////////////////////////////////
    // Spring Framework Setter Injection //
    ///////////////////////////////////////

    private MemberDao memberDao;
    private BoardDao  boardDao;
    private ContactDao contactDao;
    private CountryDao countryDao;
    private JavaMailSender mailSender;



    public void setMemberDao(MemberDaoImpl memberDao) {
        this.memberDao = memberDao;
    }

    public void setBoardDao(BoardDaoImpl boardDao) {
        this.boardDao = boardDao;
    }

    public void setContactDao(ContactDaoImpl contactDao){
        this.contactDao = contactDao;
    }

    public void setCountryDao(CountryDao countryDao) {
        this.countryDao = countryDao;
    }

    public void setMailSender(JavaMailSender mailSender){
        this.mailSender = mailSender;
    }
}
